//
//  MessageViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 16/3/7.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "MessageViewController.h"
#import "messageTableviewCell.h"
#import "system_MessageViewController.h"
#import "chatViewController.h"
#import "messageHeaderView.h"
#import "UIViewExt.h"
#import "EMSDK.h"
#import "EMConversation.h"

@interface MessageViewController ()<UITableViewDelegate, UITableViewDataSource,EMChatManagerDelegate,EMGroupManagerDelegate>
{
    dispatch_queue_t refreshQueue;
}
@property (strong, nonatomic) UITableView *tableview;
@property (strong, nonatomic) messageHeaderView *header;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (assign, nonatomic) NSInteger sysMessageCount;
@end

@implementation MessageViewController
- (instancetype)initWithSystemMessageCount:(NSInteger)Count
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.dataArray = [[NSMutableArray alloc] init];
        self.sysMessageCount = Count;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"私信";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 64) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    
    self.header = [[messageHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, ([UIScreen mainScreen].bounds.size.height - 64 - 45) / 8)withCount:_sysMessageCount];
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushSystemMessageList)];
    [_header addGestureRecognizer:recognizer];
    _tableview.tableHeaderView = _header;

    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 30, 30)];
    [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backItem;
    [self refreshAndSortView];
}

- (void)pushSystemMessageList
{
    NSInteger badgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - _sysMessageCount;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeNumber];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"checkUnreadMessageCount" object:@"0"];
    system_MessageViewController *messageController = [[system_MessageViewController alloc] init];
    [self.navigationController pushViewController:messageController animated:YES];
    _header.countLabel.text = @"你有 0 条新消息";
    _header.countLabel.textColor = [UIColor grayColor];
}
- (void)backTo
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    [self refreshAndSortView];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[EMClient sharedClient].chatManager removeDelegate:self];
    [[EMClient sharedClient].groupManager removeDelegate:self];
    
}
#pragma mark -
#pragma mark 环信
-(void)refreshAndSortView
{
    __weak typeof(self) weakself = self;
        NSArray *conversations = [[EMClient sharedClient].chatManager loadAllConversationsFromDB];
        NSArray* sorted = [conversations sortedArrayUsingComparator:
                           ^(EMConversation *obj1, EMConversation* obj2){
                               EMMessage *message1 = [obj1 latestMessage];
                               EMMessage *message2 = [obj2 latestMessage];
                               if(message1.timestamp > message2.timestamp) {
                                   return(NSComparisonResult)NSOrderedAscending;
                               }else {
                                   return(NSComparisonResult)NSOrderedDescending;
                               }
                           }];
        
        
        
        [weakself.dataArray removeAllObjects];
        for (EMConversation *converstion in sorted) {
            if ([converstion latestMessage]) {

                [weakself.dataArray addObject:converstion];
            }
        }
        [weakself.tableview reloadData];
}

- (void)didUpdateGroupList:(NSArray *)aGroupList
{
    [self refreshAndSortView];
}

- (void)didReceiveMessages:(NSArray *)aMessages
{
    [self refreshAndSortView];
}
#pragma mark - tableview

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     return ([UIScreen mainScreen].bounds.size.height - 64 - 45) / 8;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *cellIdentifier = @"message";
    // 检查表视图中是否存在闲置的单元格
    messageTableviewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[messageTableviewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.separatorColor = tableView.separatorColor;
    cell.conversation = _dataArray[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EMConversation *conversation = _dataArray[indexPath.row];
    chatViewController *chatController = [[chatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
    messageTableviewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    chatController.chatName = cell.username.text;
    [self.navigationController pushViewController:chatController animated:YES];
    NSInteger badgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - conversation.unreadMessagesCount;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeNumber];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  YES;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return   UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    EMConversation *conversation = _dataArray[indexPath.row];
    [[EMClient sharedClient].chatManager deleteConversation:conversation.conversationId deleteMessages:YES];
    [_dataArray removeObjectAtIndex:indexPath.row];
    [_tableview reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
